package com.werdior.shiro.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.werdior.common.annotation.SysLog;
import com.werdior.common.util.Constant;
import com.werdior.common.util.R;
import com.werdior.shiro.entity.User;
import com.werdior.shiro.entity.vo.UserVO;
import com.werdior.shiro.service.IUserRoleService;
import com.werdior.shiro.service.IUserService;
import com.xiaoleilu.hutool.convert.Convert;
import com.xiaoleilu.hutool.lang.Assert;
import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.ui.Model;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * user 用户表 前端控制器
 * </p>
 *
 * @author werdior
 * @since 2017-12-23
 */
@RestController
@RequestMapping("/shiro/user")
public class UserController  extends  AbstractController{

    @Autowired
    private IUserService userService;

    @Autowired
    private IUserRoleService userRoleService;

    /**
     * 获取登录的用户信息
     */
    @RequestMapping("/info")
    public R info() {
        UserVO user=new UserVO();
        user.setNickname(getUser().getNickname());
        user.setUsername(getUser().getUsername());
        user.setId(getUserId());
        user.setPassword(getUser().getPassword());
        return R.ok().put("user", user);
    }

    /**
     * 修改登录用户密码
     */
    @SysLog("修改密码")
    @RequestMapping("/password")
    public R password(String password, String newPassword) {
        Assert.notBlank(newPassword, "新密码不为能空");
        Assert.notBlank(password, "旧密码不为能空");
        password = new SimpleHash("MD5", password, getUser().getSalt()).toString();

        newPassword = new SimpleHash("MD5", newPassword, getUser().getSalt()).toString();

        //更新密码
        boolean count = userService.updatePassword(getUserId(), password, newPassword);
        if (!count) {
            return R.error("原密码不正确");
        }
        return R.ok();
    }

    /**
     *添加用户
     */
    @SysLog("添加用户")
    @PostMapping("/adduser")
    @RequiresPermissions("user:add")
    public R addUser(@RequestBody User user){
        boolean ifuser = userService.addUser(user);
        if (ifuser == false) {
            return R.error("添加用户失败");
        }
        return R.ok();
    }

    /**
     *修改用户信息
     */
    @SysLog("修改用户信息")
    @PostMapping("/edituser")
    @RequiresPermissions("user:update")
    public R editUser(@RequestBody User user){
        boolean editUser=userService.updateUser(user);
        if (editUser == false) {
            return R.error("修改失败");
        }
        return R.ok();
    }

    /**
     *查询用户详细信息
     */
    @SysLog("查询用户详细信息")
    @RequestMapping("/info/{userId}")
    public R userInfo(@PathVariable("userId") Long userId){
        User userInfo=userService.selectById(userId);
        //获取用户所属的角色列表
        List<Long> roleIdList = userRoleService.queryRoleIdList(userId);
        userInfo.setRoleIdList(roleIdList);
        return R.ok().put("userList",userInfo);
    }

    /**
     *查询所有用户
     */
    @SysLog("查询用户所有信息")
    @GetMapping("/userlist")
    @RequiresPermissions("user:show")
    public R userList(@RequestParam Map<String, Object> params){
        Map<String,Object> map=new HashMap<>();
        EntityWrapper<User> wrapper = new EntityWrapper<User>();
        //只有超级管理员，才能查看所有管理员列表
        if (getUserId() != Constant.SUPER_ADMIN) {
            params.put("create_id", getUserId());
            wrapper.where("create_id={0}", getUserId());
        }
        if (Convert.toBool(params.get("ispage"))==true){
            if (params.containsKey("username")) {
                wrapper.like("username", params.get("username").toString());
            }
            Page<User> userPage = userService.selectPage(new Page<>(Convert.toInt(params.get("page")), Convert.toInt(params.get("limit"))), wrapper);
            map.put("count", userService.selectCount(wrapper));
            map.put("data", userPage.getRecords());
        }
        else {
            map.put("userList",userService.selectAll());
        }
        return R.ok(map);

    }
    /**
     *根据id删除用户信息
     */
    @GetMapping("/delectUser")
    public R deleteUser( Long[] userIds){

       // System.out.print("userIds"+userIds);
        if (ArrayUtils.contains(userIds, 2L)) {
            return R.error("系统管理员不能删除");
        }

        if (ArrayUtils.contains(userIds, getUserId())) {
            return R.error("当前用户不能删除");
        }
       boolean userInfo=userService.deleteUserByIdAndRole(userIds);
        if (userInfo == false) {
            return R.error("删除失败");
        }

        return R.ok();
    }

}
